package com.kzw.dao;

import java.util.List;

import my.db.QueryHelper;
import my.vo.Page;

import com.kzw.entity.Student;

/**
 * 对单个表进行增删改查，与业务无关
 * */
public class StudentDao {

	/**
	 * 增加
	 * */
	public void save(Student student) {
		String sql = "insert into student values(null,?,?,?,?)";
		QueryHelper.update(sql, student.getName(), student.getSno(), student.getClazzId(), student.getPicPath());
	}
	
	/**
	 * 修改
	 * */
	public void update(Student student) {
		String sql = "update student set name=?, sno=?, clazzId=?, picPath=? where id=?";
		QueryHelper.update(sql, student.getName(), student.getSno(), student.getClazzId(), student.getPicPath(), student.getId());
	}
	
	/**
	 * 删除
	 * */
	public void remove(Long id) {
		String sql = "delete from student where id=?";
		QueryHelper.update(sql, id);
	}
	
	/**
	 * 按主键查询
	 * */
	public Student findById(Long id) {
		String sql = "select * from student where id=?";
		return QueryHelper.queryUnique(Student.class, sql, id);
	}
	
	/**
	 * 查询所有
	 * */
	public List<Student> findAll() {
		String sql = "select x.*, y.name cname from student x, clazz y where x.clazzId=y.id";
		return QueryHelper.query(Student.class, sql);
	}
	
	/**
	 * 按属性查询
	 * */
	public List<Student> findBy(String prop, Object value) {
		String sql = "select * from student where " + prop +"=?";
		return QueryHelper.query(Student.class, sql, value);
	}

	/**
	 * 分页查找
	 * */
	public void findPage(Page<Student> page) {
		String sql = "select x.*, y.name cname from student x, clazz y where x.clazzId=y.id";

		// 需要计算总共有多少条记录
		String sql2 = sql.toLowerCase().replaceFirst("select .*? from", "select count(*) from");
		long count = QueryHelper.stat(sql2);
		page.setTotalCount(Integer.parseInt(count+""));
		
		List<Student> list = QueryHelper.queryPage(Student.class, sql, page.getPageNo(), page.getPageSize());
		page.setResult(list);
	}
}
